
#include "util.h"



QImage Util::IplImage2QImage(IplImage* iplImg)
{
   int h = iplImg->height;
   int w = iplImg->width;
   int channels = iplImg->nChannels;
   char *data = iplImg->imageData;
   
   QImage img(w, h, QImage::Format_ARGB32);

   
   for(int y = 0; y < h; y++, data += iplImg->widthStep)
   {
      for(int x = 0; x < w; x++)
      {
	 char r = 0, g = 0, b = 0, a = 0;
	 if (channels == 1)
	 {
	    r = data[x * channels];
	    g = data[x * channels];
	    b = data[x * channels];
	 }
	 else if (channels == 3 || channels == 4)
	 {
	    r = data[x * channels + 2];
	    g = data[x * channels + 1];
	    b = data[x * channels];
	 }

	 if (channels == 4)
	 {
	    a = data[x * channels + 3];
	    img.setPixel(x, y, qRgba(r, g, b, a));
	 }
	 else
	 {
	    img.setPixel(x, y, qRgb(r, g, b));
	 }
      }
   }
   
   return img;
}






IplImage *Util::QImage2IplImage(const QImage& image)
{
    if( image.isNull() ) return 0;
    IplImage *imgHeader = cvCreateImageHeader( cvSize(image.width(), image.width()), IPL_DEPTH_8U, 4);
    imgHeader->imageData = (char*) image.bits();

    uchar* newdata = (uchar*) malloc(sizeof(uchar) * image.byteCount());
    memcpy(newdata, image.bits(), image.byteCount());
    imgHeader->imageData = (char*) newdata;
    //cvClo
    return imgHeader;
}





cv::Mat Util::QImage2Mat(const QImage& image)
{
    return cv::Mat(image.height(), image.width(), CV_8UC4, (uchar*)image.bits(), image.bytesPerLine());
}
